package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/user/model"

	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// UserFollowRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customUserFollowRepository.
	UserFollowRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.UserFollowRelationship, error) // ##24.11.30##
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.UserFollowRelationship, error) // ##24.11.30##
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.UserFollowRelationship, int64, error) // ##24.11.30##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.UserFollowRelationship,
			//rel *model.UserFollowRel,
		) error // ##24.11.30##
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.UserFollowRelationship,
			rel *model.UserFollowRel,
		) error
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error // ##24.11.30##
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error
	}

	customUserFollowRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheIdExpirePrefix string
	}
)

// NewUserFollowRepository returns a repository for the database table.
func NewUserFollowRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) UserFollowRepository {
	return &customUserFollowRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:cms:posts:id:",
		cacheIdExpirePrefix: "cache:cms:posts:id:expire:",
	}
}

func (r *customUserFollowRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.UserFollowRelationship, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.UserFollowRelationship
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindUserFollowRelationship(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.UserFollowRelationship) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customUserFollowRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.UserFollowRelationship, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindUserFollowRelationship(ctx, db, id)
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customUserFollowRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.UserFollowRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.UserFollowRelationshipColumns.ID+" DESC"))
					mods = append(mods, model.UserFollowRelationshipWhere.ID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.UserFollowRelationshipColumns.ID+" ASC"))
					mods = append(mods, model.UserFollowRelationshipWhere.ID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
			//case "search":
			//	if val, ok := v.(string); ok && len(val) > 0 { // 搜索
			//		likeVal := fmt.Sprintf("%%%s%%", val)
			//		mods = append(mods, qm.Where(fmt.Sprintf(
			//			"(%s LIKE ? OR %s LIKE ?)",
			//			model.UserFollowRelationshipColumns.PostTitle,
			//			model.UserFollowRelationshipColumns.PostName), likeVal, likeVal))
			//	}
			//case "statistic":
			//	if val, ok := v.(string); ok && val == "1" { // 按 PostStatus 统计
			//		statistic = true
			//	}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.UserFollowRelationshipColumns.ID:
			mods = append(mods, modelx.GetIntMods(model.UserFollowRelationshipColumns.ID, opMap)...)
		case model.UserFollowRelationshipColumns.UserID:
			mods = append(mods, modelx.GetIntMods(model.UserFollowRelationshipColumns.UserID, opMap)...)
		case model.UserFollowRelationshipColumns.FriendID:
			mods = append(mods, modelx.GetIntMods(model.UserFollowRelationshipColumns.FriendID, opMap)...)
		case model.UserFollowRelationshipColumns.FollowChannel:
			mods = append(mods, modelx.GetIntMods(model.UserFollowRelationshipColumns.FollowChannel, opMap)...)
		case model.UserFollowRelationshipColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.UserFollowRelationshipColumns.Status, opMap)...)
		case model.UserFollowRelationshipColumns.DelStatus:
			mods = append(mods, modelx.GetIntMods(model.UserFollowRelationshipColumns.DelStatus, opMap)...)
		case model.UserFollowRelationshipColumns.LastCreatedAt:
			mods = append(mods, modelx.GetTimeMods(model.UserFollowRelationshipColumns.LastCreatedAt, opMap)...)
		case model.UserFollowRelationshipColumns.CreatedAt:
			mods = append(mods, modelx.GetTimeMods(model.UserFollowRelationshipColumns.CreatedAt, opMap)...)
		case model.UserFollowRelationshipColumns.UpdatedAt:
			mods = append(mods, modelx.GetTimeMods(model.UserFollowRelationshipColumns.UpdatedAt, opMap)...)
		case model.UserFollowRelationshipColumns.DeletedAt:
			mods = append(mods, modelx.GetTimeMods(model.UserFollowRelationshipColumns.DeletedAt, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.UserFollowRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.UserFollowRelationshipColumns.ID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.UserFollowRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customUserFollowRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.UserFollowRelationship,
	// rel *model.UserFollowRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserFollowRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.UserFollowRelationship,
	rel *model.UserFollowRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		if data != nil {
			blacklist := []string{
				model.UserFollowRelationshipColumns.ID,
				model.UserFollowRelationshipColumns.UserID,
				model.UserFollowRelationshipColumns.FriendID,
				model.UserFollowRelationshipColumns.DeletedAt,
			}
			if rel != nil && len(rel.Blacklist) > 0 {
				blacklist = append(blacklist, rel.Blacklist...)
			}
			rowsAff, err := data.Update(ctx, db, boil.Blacklist(blacklist...))
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}
		}

		if rel == nil {
			return nil
		}
		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserFollowRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status == uint16(globalkey.UserFollowStatusDeleted) {
		return nil
	}

	data.DelStatus = data.Status
	data.Status = uint16(globalkey.UserFollowStatusDeleted)
	data.DeletedAt = null.TimeFrom(time.Now())
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.UserFollowRelationshipColumns.DelStatus,
			model.UserFollowRelationshipColumns.Status,
			model.UserFollowRelationshipColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserFollowRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status != uint16(globalkey.UserFollowStatusDeleted) {
		return nil
	}

	data.Status = data.DelStatus
	data.DeletedAt = null.TimeFromPtr(nil)
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.UserFollowRelationshipColumns.Status,
			model.UserFollowRelationshipColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserFollowRepository) getCacheKeys(data *model.UserFollowRelationship) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.ID)
	cacheIdExpireKey := r.formatPrimaryWithExpire(data.ID)
	cacheKeys := []string{
		cacheIdKey,
		cacheIdExpireKey,
	}

	return cacheKeys
}

func (r *customUserFollowRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customUserFollowRepository) formatPrimaryWithExpire(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdExpirePrefix, primary)
}

func (r *customUserFollowRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
		resp = append(resp, r.formatPrimaryWithExpire(primary))
	}

	return resp
}

func (r *customUserFollowRepository) queryPrimary(ctx context.Context, conn *sql.DB, v any, primary any) error {
	var pid uint64
	if jsonId, ok := primary.(json.Number); ok {
		if int64Id, err := jsonId.Int64(); err == nil {
			pid = uint64(int64Id)
		} else {
			return err
		}
	}

	data, err := model.FindUserFollowRelationship(ctx, conn, pid)
	if err != nil {
		return err
	}

	*v.(*model.UserFollowRelationship) = *data

	return nil
}
